# coding=utf8
# author_: chanceyang
import json
import os
import re
import nox
env_dist = os.environ
casesDirs=["./packageAndCourse/"]
isOnJenkins=False
# os.environ['casesDirs']=""

if env_dist.get("casesDirs")!=None:
    casesDirs=env_dist.get("casesDirs").split(",")
    isOnJenkins=True
argsList=['test' for i in range(len(casesDirs))]
installIp="124.71.154.156:8081"
count=0

@nox.session(reuse_venv=True)
@nox.parametrize("caseDir",argsList)
def runChosedCases(session,caseDir):
    global installIp
    global count
    count+=1
    if casesDirs[count-1] is None or casesDirs[count-1]=="" or casesDirs[count-1]=="./":
        return
    if session.posargs:
        for arg in session.posargs:
            ip = re.match("ip=(.+)", arg)
            if ip:
                installIp = ip.group(1)
    print(casesDirs)
    print(installIp)
    session.install("-i", "http://"+installIp+"/repository/group-pypi/simple/", "--trusted-host",
                    installIp.split(":")[0], "-r", "requirements.txt")


    if count==1 and isOnJenkins==False:
        session.run("pytest", "-vv","-s", casesDirs[count-1],"--clean-alluredir", "--alluredir", "../report/xml")
    else:
        session.run("pytest", "-vv", "-s", casesDirs[count-1], "--alluredir", "../report/xml")


@nox.session(reuse_venv=True)
def GeneratorReport(session):
    session.run("allure", "generate", "--clean", "../report/xml", "-o", "../report/html")



def readFailure(path):
    listStr = os.listdir(path)
    failDict={}
    for s in listStr:
        if "result" in s:
            with open(path + "/" + s, encoding="utf8") as f:
                data = json.load(f)
                key = data.get("fullName") + data.get("name")
                if failDict.get(key) is None:
                    failDict[key] = [data.get("start"), data.get("status")]
                else:
                    if data.get("start") > failDict[key][0]:
                        failDict[key] = [data.get("start"), data.get("status")]
    resFailureSet=set()
    for key in failDict.keys():
        if failDict[key][1]=="failed":
            resFailureSet.add(key.split(".")[0])
    return list(resFailureSet)

@nox.session(reuse_venv=True)
def collectFailedCases(session):
    xmlPath = "../report/xml"
    resFailureList = readFailure(xmlPath)
    fail_models = ""
    for s in resFailureList:
        fail_models += "./" + s + "/,"
    fail_models = fail_models[:-1]
    print("存在失败用例的模块："+fail_models)
    if fail_models=="" or fail_models is None:
        with open("../report/failInfo.txt", "w", encoding="utf8") as f:
            f.write("")
        return
    with open("../report/failInfo.txt", "w", encoding="utf8") as f:
        f.write(fail_models)

@nox.session(reuse_venv=True)
def readFailedCases(session):
    try:
        listStr = os.listdir("../report")
        if "failInfo.txt" in listStr:
            with open("../report/failInfo.txt", "r", encoding="utf8") as f:
                failedCases=f.read()
                os.environ['casesDirs'] =failedCases
    except Exception as e:
        print(e)




# nox -s  runChosedCases
# nox -s  runChosedCases  GeneratorReport  -- ip=124.71.154.156:8081

# pip install --trusted-host 124.71.154.156 -i http://124.71.154.156:8081/repository/group-pypi/simple/ -r requirements.txt